<?php
/**
 * User: hjd-yao
 * Date: 2019/7/19
 * Time: 15:21
 */

namespace Shop\Http\Controllers\Pc;


use App\Helpers\SelfEncrypt;
use App\Helpers\SelfResponse;
use App\Models\Shop\ShopCouponModel;
use App\Models\Shop\UserCouponModel;
use Carbon\Carbon;
use DC\UserCenter\Models\UserWalletModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Shop\Http\Controllers\BaseController;

class UserController extends BaseController
{
    public function sideUser()
    {
        return $this->pcRender('public.right.user');
    }

    public function grabCoupon(Request $request)
    {
        $coupon_id = $request->input('coupon_id');
        $user_id = $request->input('user_id');
        $info = ShopCouponModel::where('status',1)->whereRaw('release_number>used_number')->find($coupon_id);
        if(!$info){
            return SelfResponse::error('优惠券已领完,请选择其他优惠券');
        }
        if(UserCouponModel::where('coupon_id',$coupon_id)->where('user_id',$user_id)->value('id')){
            return SelfResponse::error('该优惠券已领过');
        }
        if(ShopCouponModel::where('status',1)
            ->whereRaw('release_number>used_number')
            ->where('id',$coupon_id)->decrement('release_number',1,['used_number'=>DB::raw('`used_number`+1')])
        ){
            $userCoupon = new UserCouponModel();
            $userCoupon->coupon_sn = SelfEncrypt::createSn('C',10);
            $userCoupon->face_value = $info->face_value;
            $userCoupon->store_id = $info->store_id;
            $userCoupon->coupon_type = $info->coupon_type;
            $userCoupon->activity_type = $info->activity_type;
            $userCoupon->use_condition = $info->use_condition;
            $userCoupon->lifetime =  Carbon::now()->timestamp + $info->lifetime*24*3600;
            $userCoupon->status = 0;
            $userCoupon->coupon_id = $coupon_id;
            $userCoupon->user_id = $request->input('user_id');
            $userCoupon->save();
            return SelfResponse::success('优惠券领取成功');
        }
        return SelfResponse::error('优惠券领取失败,请稍后再试');
    }

    public function myWallet(Request $request)
    {
        $user_id = $request->input('user_id');

        return $this->pcRender('user.wallet',[
            'wallet'=>UserWalletModel::find($user_id),
        ]);
    }
}